import { Models } from "../common/typings/model"
import HttpErrors from "../core/HttpException"
import dbConfig from '../config/dbConfig'
import logger from './logs'
const catchError = async (ctx: Models.Ctx,next: Function)=> {
    try {
        await next()
        logger.info(ctx.method,ctx.originalUrl)
    
    }
    catch (error: any) {
        // 需要返回的信息
        // HTTP Status Code 
        // message
        // error_code 详细错误，开发者自己定义
        // 错误类型：已知错误、未知错误
        let isHttpException = error instanceof HttpErrors.HttpException
        let isDev = dbConfig.environment === 'dev'

        if(isDev && !isHttpException) {//已知异常
            if(dbConfig.environment === 'dev') {
                
                throw error
            }
            
        }
        else if(!isDev && !isHttpException) {
            ctx.body = {
                msg:'未知错误',
                errorCode: 9999,
                requestUrl: `${ctx.method} ${ctx.path}`
            }
            ctx.status = 500
        }
        if(isHttpException) {
            if(error.responseType){
                ctx.response.type = error.responseType
            }
            if(error.isBuffer){
                ctx.body = error.data
            }
            else {
                ctx.body = {
                    msg: error.message,
                    errorCode: error.errorCode,
                    requestUrl: `${ctx.method} ${ctx.path}`,
                    result: error.data,
                    
                }
            }
            
            ctx.status = error.code
            if(error instanceof HttpErrors.Success){
                logger.info(ctx.method,ctx.originalUrl)
            }
            else {
                logger.error(ctx.method,ctx.originalUrl,error)
            }
        }
        else {
            logger.error(ctx.method,ctx.originalUrl,error)
        }
        
    
        
    }
}
export {
    catchError
}
